import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:im_demo/app/data/chat/action_type.dart';
import 'package:im_demo/app/data/chat/message_type.dart';
import 'package:im_demo/app/data/chat/single_message.dart';

import '../../../../utils/logger_util.dart';
import '../../../services/websocket_service.dart';

class SingleChatController extends GetxController {
  var editTextController = TextEditingController();
  var urlEditTextController = TextEditingController();
  var tokenEditTextController = TextEditingController();

  var userIdEditTextController = TextEditingController();
  var targetUserIdEditTextController = TextEditingController();

  final messageList = <SingleMessage>[].obs;
  final inputText = ''.obs;

  static const defaultUrl = 'ws://192.168.1.183:8090/ws';
  static const token = '';

  @override
  void onInit() {
    super.onInit();
    editTextController.addListener(() {});
    Get.put(WebSocketService());

    // _connectWebsocket();
  }

  @override
  void onReady() {
    super.onReady();

    updateUrlInputText(defaultUrl);
  }

  @override
  void onClose() {
    _disconnectWebsocket();
    super.onClose();
  }

  void updateInputText(String text) {
    editTextController.text = text;
  }

  void cleanInputText() {
    editTextController.clear();
  }

  void updateUrlInputText(String text) {
    urlEditTextController.text = text;
  }

  void cleanUrlInputText() {
    urlEditTextController.clear();
  }

  void updateTokenInputText(String text) {
    tokenEditTextController.text = text;
  }

  void cleanTokenInputText() {
    tokenEditTextController.clear();
  }

  void updateUserIdInputText(String text) {
    userIdEditTextController.text = text;
  }

  void cleanUserIdInputText() {
    userIdEditTextController.clear();
  }

  void updateTargetUserIdInputText(String text) {
    targetUserIdEditTextController.text = text;
  }

  void cleanTargetUserIdInputText() {
    targetUserIdEditTextController.clear();
  }

  void handlerMessage() {}

  void connectWebsocket() {
    _connectWebsocket();
  }

  void _connectWebsocket() async {
    SingleMessage message = SingleMessage(
      userId: -1,
      messageType: MessageType.LOGIN,
      targetUserId: -1,
      message: '开始连接,请稍等...',
    );
    _addMessage(message);

    final url =
        urlEditTextController.text.isEmpty
            ? defaultUrl
            : urlEditTextController.text;
    logE('_connectWebsocket url:$url');

    await WebSocketService.to.connect(url, token);

    if (WebSocketService.to.isConnected.value) {
      SingleMessage message = SingleMessage(
        userId: -1,
        messageType: MessageType.LOGIN,
        targetUserId: -1,
        message: '已连接',
      );

      _addMessage(message);
    }

    _setupWebSocket();
  }

  void disconnectWebsocket() {
    _disconnectWebsocket();
  }

  void _disconnectWebsocket() {
    WebSocketService.to.disconnect();

    SingleMessage message = SingleMessage(
      userId: -1,
      messageType: MessageType.LOGIN,
      targetUserId: -1,
      message: '已断开连接',
    );
    _addMessage(message);
  }

  void _setupWebSocket() {
    WebSocketService.to.stream.listen(
      (data) {
        logE('_setupWebSocket()-->data:$data');

        // Message message = Message.fromJson(data);
        SingleMessage msg = SingleMessage(
          userId: -1,
          messageType: MessageType.LOGIN,
          targetUserId: -1,
          message: data,
        );

        _addMessage(msg);
      },
      onDone: () => _disconnectWebsocket(),
      onError: (err) {
        logE('_setupWebSocket()-->onError:$err');
      },
    );
  }

  void login() {
    if (userIdEditTextController.text.isEmpty) {
      Get.snackbar('', '请输入UserId');
      return;
    }

    if (targetUserIdEditTextController.text.isEmpty) {
      Get.snackbar('', '请输入TargetUserId');
      return;
    }

    final userId = int.parse(userIdEditTextController.text);
    final targetUserId = int.parse(targetUserIdEditTextController.text);
    SingleMessage message = SingleMessage(
      userId: userId,
      messageType: MessageType.LOGIN,
      targetUserId: targetUserId,
    );
    logE('_login()->message:${jsonEncode(message.toJson())}');

    WebSocketService.to.sendMessage(jsonEncode(message.toJson()));
  }

  void _addMessage(SingleMessage message) {
    messageList.insert(0, message);
  }

  void sendMessage(String text) {
    if (text.isEmpty) {
      Get.snackbar('', '请输入发送内容');
      return;
    }

    SingleMessage message = SingleMessage(
      userId: int.parse(userIdEditTextController.text),
      messageType: MessageType.SEND_MESSAGE,
      targetUserId: int.parse(targetUserIdEditTextController.text),
      message: text,
    );

    logE('sendMessage()-->message:${jsonEncode(message.toJson())}');

    // WebSocketService.to.sendMessage(message);
    WebSocketService.to.sendMessage(jsonEncode(message.toJson()));

    _addMessage(message);

    editTextController.clear();
  }
}
